package com.project.hqshorttaxi.controller;

import com.github.pagehelper.PageHelper;
import com.project.hqshorttaxi.aop.TagLog;
import com.project.hqshorttaxi.dto.*;
import com.project.hqshorttaxi.entity.Login;
import com.project.hqshorttaxi.entity.OperationLog;
import com.project.hqshorttaxi.entity.ShortDistance;
import com.project.hqshorttaxi.entity.TurnstileData;
import com.project.hqshorttaxi.service.*;
import com.project.hqshorttaxi.util.HttpResult;
import com.project.hqshorttaxi.util.HttpUtil;
import com.project.hqshorttaxi.util.PageInfo;
import com.project.hqshorttaxi.util.RestResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/shortdistance/")
public class ShortDistanceController {

    @Resource
    ShortDistanceService shortDistanceService;
    @Resource
    TurnstileDataService turnstileDataService;
    @Resource
    PlateCameraService plateCameraService;
    @Resource
    OperationLogService operationLogService;
    @Resource
    LoginService loginService;
    @Resource
    ConfigDto configDto;

    /**
     * 新增
     */
    @PostMapping("add")
    public RestResult add(@RequestBody ShortDistance param) {
        try {
            shortDistanceService.insert(param);
            return RestResult.ok();
        } catch (Exception e) {
            return RestResult.error(e.getMessage());
        }
    }

    /**
     * 列表
     */
    @PostMapping("page")
    @TagLog(operation = 0, content = "查询短途列表")
    public RestResult page(@RequestBody ShortDistanceParam param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        return RestResult.ok(new PageInfo<>(shortDistanceService.list(param)));
    }

    /**
     * 根据ID获取
     */
    @GetMapping("{id}")
    @TagLog(operation = 0, content = "根据ID获取短途详细信息")
    public RestResult pageById(@PathVariable Integer id) {
        return RestResult.ok(shortDistanceService.getById(id));
    }

    /**
     * 根据ID获取道闸判断记录
     */
    @GetMapping("turnstile/{id}")
    @TagLog(operation = 0, content = "根据ID获取道闸详细信息")
    public RestResult turnstileById(@PathVariable Integer id) {
        return RestResult.ok(turnstileDataService.getById(id));
    }

    /**
     * 根据ID获取牌照识别记录
     */
    @GetMapping("platecamera/{id}")
    @TagLog(operation = 0, content = "根据ID获取车牌照片详细信息")
    public RestResult plateCameraById(@PathVariable Integer id) {
        return RestResult.ok(plateCameraService.getById(id));
    }

    @PostMapping("manual/post")
    @TagLog(operation = 2, content = "手动验证")
    public RestResult ManualPost(@RequestHeader(value = "authorization") String token, @RequestBody HttpPostParam param) {
        try {
            Login entity = loginService.getByToken(token);
            if (entity == null) {
                return RestResult.error("用户不存在");
            }
            OperationLog operationLog = new OperationLog();
            operationLog.setOperation(0);
            operationLog.setParkingNo(param.getParkingNo());
            operationLog.setPlateNumber(param.getPlateNumber());
            operationLog.setCreateUser(entity.getUserName());
            operationLog.setCreateTime(new Date());
            String url = configDto.getManaulPostUrl();
            HttpUtil httpUtil = new HttpUtil(url, configDto.getTimeout());
            HttpResult httpResult = httpUtil.postUrl(param);
            if (httpResult.getResCode() == 0) {
                operationLog.setResult("成功");
                operationLogService.insert(operationLog);
                return RestResult.ok();
            } else {
                operationLog.setResult(httpResult.getResMsg());
                operationLogService.insert(operationLog);
                return RestResult.error(httpResult.getResMsg());
            }
        } catch (Exception e) {
            return RestResult.error(e.getMessage());
        }
    }

    @PostMapping("temp/post")
    @TagLog(operation = 2, content = "临时放行")
    public RestResult TempPost(@RequestHeader(value = "authorization") String token, @RequestBody HttpPostParam param) {
        try {
            Login entity = loginService.getByToken(token);
            if (entity == null) {
                return RestResult.error("用户不存在");
            }
            OperationLog operationLog = new OperationLog();
            operationLog.setOperation(1);
            operationLog.setParkingNo(param.getParkingNo());
            operationLog.setPlateNumber(param.getPlateNumber());
            operationLog.setCreateUser(entity.getUserName());
            operationLog.setCreateTime(new Date());
            String url1 = configDto.getOpenTurnstileUrl();
            HttpUtil httpUtil1 = new HttpUtil(url1, configDto.getTimeout());
            HttpResult httpResult1 = httpUtil1.postUrl(param);
            if (httpResult1.getResCode() == 0) {
                TurnstileData turnstileData = new TurnstileData();
                turnstileData.setPlateNumber(param.getPlateNumber());
                turnstileData.setParkingNo(param.getParkingNo());
                turnstileData.setShortDistanceID(0);
                turnstileData.setTurnTime(new Date());
                turnstileData.setOpDate(new Date());
                turnstileDataService.insert(turnstileData);
                operationLog.setResult("成功");
                operationLogService.insert(operationLog);
                String url2 = configDto.getPushLedScreenUrl();
                HttpUtil httpUtil2 = new HttpUtil(url2, configDto.getTimeout());
                HttpResult httpResult2 = httpUtil2.postUrl(param);
                if (httpResult2.getResCode() == 0) {
                    return RestResult.ok();
                } else {
                    operationLog.setResult(operationLog.getResult() + "推屏失败:" + httpResult2.getResMsg());
                    operationLogService.update(operationLog);
                    return RestResult.error(httpResult2.getResMsg());
                }
            } else {
                operationLog.setResult(httpResult1.getResMsg());
                operationLogService.insert(operationLog);
                return RestResult.error(httpResult1.getResMsg());
            }
        } catch (Exception e) {
            return RestResult.error(e.getMessage());
        }
    }

    /**
     * 统计列表
     */
    @PostMapping("total/page")
    @TagLog(operation = 0, content = "查询短途统计列表")
    public RestResult total(@RequestBody ShortDistanceStatParam param) {
        List<ShortDistanceStatPageDto> list = new ArrayList<>();
        // 南蓄
        ShortDistanceStatPageDto dto1 = new ShortDistanceStatPageDto();
        dto1.setParkingNo(0);
        // 北蓄
        ShortDistanceStatPageDto dto2 = new ShortDistanceStatPageDto();
        dto2.setParkingNo(1);

        Integer total01 = 0;
        Integer total02 = 0;
        Integer total11 = 0;
        Integer total12 = 0;
        ShortDistanceStatPageDto.Meta meta1 = new ShortDistanceStatPageDto.Meta();
        ShortDistanceStatPageDto.Meta meta2 = new ShortDistanceStatPageDto.Meta();
        List<ShortDistanceStatDto> statDtoList = shortDistanceService.getTotal(param);
        for (ShortDistanceStatDto shortDistanceStatDto : statDtoList) {
            if (shortDistanceStatDto.getParkingNo() == 0) {
                if (shortDistanceStatDto.getRecType() == 1) {
                    meta1.setTotal1(shortDistanceStatDto.getTotal());
                    total01 = shortDistanceStatDto.getTotal();
                } else {
                    meta1.setTotal2(shortDistanceStatDto.getTotal());
                    total02 = shortDistanceStatDto.getTotal();
                }
                meta1.setTotal(total01 + total02);
                dto1.setMeta(meta1);
            } else {
                if (shortDistanceStatDto.getRecType() == 1) {
                    meta2.setTotal1(shortDistanceStatDto.getTotal());
                    total11 = shortDistanceStatDto.getTotal();
                } else {
                    meta2.setTotal2(shortDistanceStatDto.getTotal());
                    total12 = shortDistanceStatDto.getTotal();
                }
                meta2.setTotal(total11 + total12);
                dto2.setMeta(meta2);
            }
        }
        List<ShortDistanceStatDto> statDtoAllList = shortDistanceService.getTotalAll(param);
        for (ShortDistanceStatDto shortDistanceStatDto : statDtoAllList) {
            if (shortDistanceStatDto.getParkingNo() == 0) {
                if (shortDistanceStatDto.getRecType() == 1) {
                    dto1.getMeta().setTotalAll1(shortDistanceStatDto.getTotal());
                } else {
                    dto1.getMeta().setTotalAll2(shortDistanceStatDto.getTotal());
                }
            } else {
                if (shortDistanceStatDto.getRecType() == 1) {
                    dto2.getMeta().setTotalAll1(shortDistanceStatDto.getTotal());
                } else {
                    dto2.getMeta().setTotalAll2(shortDistanceStatDto.getTotal());
                }
            }
        }
        if (dto1.getMeta() == null) {
            dto1.setMeta(meta1);
        }
        if (dto2.getMeta() == null) {
            dto2.setMeta(meta2);
        }
        if (dto1.getMeta().getTotal() == null) {
            dto1.getMeta().setTotal(0);
        }
        if (dto1.getMeta().getTotal1() == null) {
            dto1.getMeta().setTotal1(0);
        }
        if (dto1.getMeta().getTotal2() == null) {
            dto1.getMeta().setTotal2(0);
        }
        if (dto2.getMeta().getTotal() == null) {
            dto2.getMeta().setTotal(0);
        }
        if (dto2.getMeta().getTotal1() == null) {
            dto2.getMeta().setTotal1(0);
        }
        if (dto2.getMeta().getTotal2() == null) {
            dto2.getMeta().setTotal2(0);
        }
        if (dto1.getMeta().getTotalAll1() == null) {
            dto1.getMeta().setTotalAll1(0);
        }
        if (dto1.getMeta().getTotalAll2() == null) {
            dto1.getMeta().setTotalAll2(0);
        }
        if (dto2.getMeta().getTotalAll1() == null) {
            dto2.getMeta().setTotalAll1(0);
        }
        if (dto2.getMeta().getTotalAll2() == null) {
            dto2.getMeta().setTotalAll2(0);
        }
        dto1.getMeta().setTotalAll1(dto1.getMeta().getTotalAll1() + dto1.getMeta().getTotalAll2());
        dto2.getMeta().setTotalAll1(dto2.getMeta().getTotalAll1() + dto2.getMeta().getTotalAll2());
        List<ShortDistanceStatDto> statDtoRefuseList = shortDistanceService.getTotalByRefuse(param);
        List<ShortDistanceStatPageDto.Type> type1List = new ArrayList<>();
        List<ShortDistanceStatPageDto.Type> type2List = new ArrayList<>();
        for (ShortDistanceStatDto shortDistanceStatDto : statDtoRefuseList) {
            ShortDistanceStatPageDto.Type type = new ShortDistanceStatPageDto.Type();
            type.setRefuseType(shortDistanceStatDto.getRefuseType());
            type.setRecType(shortDistanceStatDto.getRecType());
            type.setTotal(shortDistanceStatDto.getTotal());
            if (shortDistanceStatDto.getParkingNo() == 0) {
                type1List.add(type);
            } else {
                type2List.add(type);
            }
        }
        dto1.setTypeList(type1List);
        dto2.setTypeList(type2List);
        list.add(dto1);
        list.add(dto2);
        return RestResult.ok(list);
    }

    /**
     * 导出（拒绝记录模版）
     */
    @PostMapping("output")
    @TagLog(operation = 5, content = "导出短途列表")
    public RestResult output(@RequestBody ShortDistanceParam param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        return RestResult.ok(new PageInfo<>(shortDistanceService.getOutputList(param)));
    }
}
